<template>
  <div class="page-container">
    <h2 style="margin-bottom: 20px;">角色管理</h2>
    
    <div class="search-form">
      <t-form :data="searchForm" @submit="handleSearch" layout="inline">
        <t-row :gutter="16">
          <t-col :span="6">
            <t-form-item label="角色名称">
              <t-input v-model="searchForm.name" placeholder="请输入角色名称" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="角色标识">
              <t-input v-model="searchForm.code" placeholder="请输入角色标识" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="状态">
              <t-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <t-option value="1" label="正常" />
                <t-option value="0" label="禁用" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item>
              <t-button theme="primary" type="submit">查询</t-button>
              <t-button variant="outline" @click="handleReset">重置</t-button>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </div>
    
    <div class="table-actions">
      <t-space>
        <t-button theme="primary" @click="showCreateDialog = true">
          <template #icon><t-icon name="add" /></template>
          新增角色
        </t-button>
        <t-button variant="outline" @click="handleExport">
          <template #icon><t-icon name="download" /></template>
          导出数据
        </t-button>
      </t-space>
    </div>
    
    <t-table
      :data="roleList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
    >
      <template #status="{ row }">
        <t-tag :theme="row.status === 1 ? 'success' : 'danger'" variant="light">
          {{ row.status === 1 ? '正常' : '禁用' }}
        </t-tag>
      </template>
      
      <template #permissions="{ row }">
        <t-space>
          <t-tag v-for="permission in row.permissions" :key="permission.id" theme="primary" variant="light">
            {{ permission.name }}
          </t-tag>
        </t-space>
      </template>
      
      <template #op="{ row }">
        <t-space>
          <t-button variant="text" theme="primary" @click="handleEdit(row)">编辑</t-button>
          <t-button variant="text" theme="primary" @click="handleAssignPermissions(row)">分配权限</t-button>
          <t-popconfirm content="确定删除该角色吗？" @confirm="handleDelete(row.id)">
            <t-button variant="text" theme="danger">删除</t-button>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>
    
    <!-- 新增/编辑对话框 -->
    <t-dialog
      v-model:visible="showCreateDialog"
      :header="editRole ? '编辑角色' : '新增角色'"
      width="600px"
      @confirm="handleSubmit"
    >
      <t-form ref="formRef" :data="formData" :rules="rules" label-width="80px">
        <t-form-item label="角色名称" name="name">
          <t-input v-model="formData.name" placeholder="请输入角色名称" />
        </t-form-item>
        <t-form-item label="角色标识" name="code">
          <t-input v-model="formData.code" placeholder="请输入角色标识" />
        </t-form-item>
        <t-form-item label="描述" name="description">
          <t-textarea v-model="formData.description" placeholder="请输入角色描述" />
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="formData.status">
            <t-radio value="1">正常</t-radio>
            <t-radio value="0">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 分配权限对话框 -->
    <t-dialog
      v-model:visible="showPermissionDialog"
      header="分配权限"
      width="800px"
      @confirm="handlePermissionSubmit"
    >
      <t-tree
        :data="permissionTree"
        :value="selectedPermissions"
        expand-all
        checkable
        value-mode="all"
        @change="handlePermissionChange"
      />
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { roleAPI } from '@/api/role'
import { permissionAPI } from '@/api/permission'
import type { Role, Permission } from '@/types'

const loading = ref(false)
const roleList = ref<Role[]>([])
const permissionTree = ref<Permission[]>([])
const showCreateDialog = ref(false)
const showPermissionDialog = ref(false)
const editRole = ref<Role | null>(null)
const currentAssignRole = ref<Role | null>(null)
const selectedPermissions = ref<number[]>([])

const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

const formData = reactive({
  name: '',
  code: '',
  description: '',
  status: '1'
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
})

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'name', title: '角色名称' },
  { colKey: 'code', title: '角色标识' },
  { colKey: 'description', title: '描述' },
  { colKey: 'status', title: '状态' },
  { colKey: 'permissions', title: '权限' },
  { colKey: 'created_at', title: '创建时间' },
  { colKey: 'op', title: '操作', width: 250 }
]

const rules = {
  name: [{ required: true, message: '请输入角色名称' }],
  code: [{ required: true, message: '请输入角色标识' }]
}

const loadRoles = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const response = await roleAPI.getRoles(params)
    roleList.value = response.data
    pagination.total = response.total
  } catch (error) {
    MessagePlugin.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

const loadPermissions = async () => {
  try {
    const response = await permissionAPI.getPermissions({ page: 1, pageSize: 1000 })
    permissionTree.value = response.data
  } catch (error) {
    MessagePlugin.error('获取权限列表失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadRoles()
}

const handleReset = () => {
  Object.assign(searchForm, { name: '', code: '', status: '' })
  pagination.current = 1
  loadRoles()
}

const handlePageChange = (pageInfo: any) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  loadRoles()
}

const handleEdit = (role: Role) => {
  editRole.value = role
  Object.assign(formData, {
    name: role.name,
    code: role.code,
    description: role.description,
    status: role.status.toString()
  })
  showCreateDialog.value = true
}

const handleAssignPermissions = (role: Role) => {
  currentAssignRole.value = role
  selectedPermissions.value = role.permissions.map(p => p.id)
  showPermissionDialog.value = true
}

const handlePermissionChange = (value: number[]) => {
  selectedPermissions.value = value
}

const handleDelete = async (id: number) => {
  try {
    await roleAPI.deleteRole(id)
    MessagePlugin.success('删除成功')
    loadRoles()
  } catch (error) {
    MessagePlugin.error('删除失败')
  }
}

const handleExport = () => {
  MessagePlugin.info('导出功能开发中')
}

const handleSubmit = async () => {
  try {
    if (editRole.value) {
      await roleAPI.updateRole(editRole.value.id, formData)
      MessagePlugin.success('更新成功')
    } else {
      await roleAPI.createRole(formData)
      MessagePlugin.success('创建成功')
    }
    showCreateDialog.value = false
    loadRoles()
  } catch (error) {
    MessagePlugin.error(editRole.value ? '更新失败' : '创建失败')
  }
}

const handlePermissionSubmit = async () => {
  if (!currentAssignRole.value) return
  
  try {
    await roleAPI.assignPermissions(currentAssignRole.value.id, selectedPermissions.value)
    MessagePlugin.success('权限分配成功')
    showPermissionDialog.value = false
    loadRoles()
  } catch (error) {
    MessagePlugin.error('权限分配失败')
  }
}

onMounted(() => {
  loadRoles()
  loadPermissions()
})
</script>